<?php

namespace backend\controllers;

use common\helpers\AdminExportApi;
use common\helpers\commonApi;
use common\models\Admin;
use common\models\Loginlog;
use common\models\Role;
use common\services\AdminRoleService;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * 人员管理控制器
 * Class AdminController
 * @package backend\controllers
 */
class AdminController extends BaseController
{
    public function init()
    {
        parent::init();
        $this->model = Admin::class;
    }

    public function actionIndex()
    {
        if (Yii::$app->request->isPost) {
            $where = [];
            $return = parent::actionIndex(true, $where);
            $list = $return['data'];
            foreach ($list as $key => $val) {
                $structNameStr = '';
                $roleNameStr = '';
                $roleList = AdminRoleService::getListByAdmin($val['id']);
                if ($roleList) {
                    $roleNameArr = ArrayHelper::getColumn($roleList, 'name');
                    $roleNameStr = implode(',', $roleNameArr);
                }
                $val['rolename'] = $roleNameStr;
                $val['structname'] = $structNameStr;
                $list[$key] = $val;
            }
            $return['data'] = $list;
            return $return;
        } else {
            return parent::actionIndex();
        }
    }

    public function actionAdd()
    {
        if (IS_RENDER) {
            Yii::$app->view->params['roleList'] = Role::find()->asArray()->all();
            return parent::actionAdd();
        } else {
            $post = Yii::$app->request->post();
            $model = new Admin();
            if ($model->load($post, '') && $model->validate()) {
                if (!$model->realname) $model->realname = $model->username;
                if (!$model->password) {
                    $model->password = '123456';
                }
                $model->password = Yii::$app->security->generatePasswordHash($model->password);
                if ($model->save(false)) {
                    $roles = $post['roles'] ?: '';
                    AdminRoleService::update($model->id, $roles);
                    return commonApi::message('添加成功', true);
                }
            }
            return commonApi::message(commonApi::getModelError($model), false);
        }
    }

    public function actionEdit()
    {
        if (IS_RENDER) {
            $info = [];
            $id = intval(Yii::$app->request->get('id', 0));
            if ($id) {
                $info = Admin::findOne($id);
            }
            if (empty($info)) {
                return $this->tError('参数或信息错误');
            }
            $roles = $info->roles;
            $info = $info->toArray();

            $structid = [];
            $structname = [];
            $info['structid'] = implode(',', $structid);
            $info['structname'] = implode(',', $structname);

            $roleid = [];
            foreach ($roles as $val) {
                $roleid[] = $val['id'];
            }
            $info['roleid'] = implode(',', $roleid);

            Yii::$app->view->params['roleList'] = Role::find()->asArray()->all();
            return $this->render('', ['info' => $info]);
        } else {
            $post = Yii::$app->request->post();
            if (!isset($post['id']) || !$post['id']) {
                return commonApi::message('参数错误', false);
            }
            $model = Admin::findOne($post['id']);
            if ($model->load($post, '') && $model->validate()) {
                if (!$model->realname) $model->realname = $model->username;
                if ($model->password) {
                    $model->password = Yii::$app->security->generatePasswordHash($model->password);
                } else {
                    $model->password = $model->oldAttributes['password'];
                }
                if ($model->save(false)) {
                    $roles = $post['roles'] ?: '';
                    AdminRoleService::update($model->id, $roles);
                    return commonApi::message('添加成功', true);
                }
            }
            return commonApi::message(commonApi::getModelError($model), false);
        }
    }

    public function actionInfo()
    {
        $model = Admin::find()->where(['id' => Yii::$app->user->id])->one();
        $session = Yii::$app->session->get(Yii::$app->params['adminLoginSession']);
        $roles = $session['role']['name'] ? implode(',', $session['role']['name']) : '';
        return $this->render('', ['info' => $model, 'roles' => $roles]);
    }

    public function actionLoginLog()
    {
        if (Yii::$app->request->isPost) {
            // 获取参数
            $argList = func_get_args();
            $pageList = $argList[0]??true;
            $extMap = $argList[1]??[];
            $extSort = $argList[2]??[];

            $map = [];
            $order_column = 'id';
            $order_sort = 'asc';
            $pageNum = 1;
            $pageSize = defined('PAGE_LIMIT') ? PAGE_LIMIT : 10;
            $total = 0;

            $param = \Yii::$app->request->post();
            if ($param) {
                //表单的条件 where 的条件
                if (!empty($param['where']) && is_array($param['where'])) {
                    foreach ($param['where'] as $paramField => $paramValue) {
                        $paramValue = trim($paramValue);
                        if ($paramValue !== '') {
                            $map[] = [$paramField => $paramValue];
                        }
                    }
                }
                //表单的条件 like 的条件
                if (!empty($param['like']) && is_array($param['like'])) {
                    foreach ($param['like'] as $paramField => $paramValue) {
                        $paramValue = trim($paramValue);
                        if ($paramValue !== '') {
                            $map[] = ['like', $paramField, $paramValue];
                        }
                    }
                }
                //表单的条件 between 的条件
                if (!empty($param['between']) && is_array($param['between'])) {
                    foreach ($param['between'] as $paramField => $paramValue) {
                        if (is_array($paramValue) && count($paramValue) > 1) {
                            $start = $paramValue['start'];
                            $end = $paramValue['end'];
                            if ($start || $end) {
                                if ($start && $end) {
                                    $map[] = ['between', $paramField, $start, $end];
                                } elseif ($start) {
                                    $map[] = ['>', $paramField, $start];
                                } elseif ($end) {
                                    $map[] = ['<', $paramField, $end];
                                }
                            }
                        }
                    }
                }
                //表单的条件 findinset 的条件
                if (!empty($param['findinset']) && is_array($param['findinset'])) {
                    foreach ($param['findinset'] as $paramField => $paramValue) {
                        $paramValue = trim($paramValue);
                        if ($paramValue !== '') {
                            $map[] = [$paramField ,'findinset', $paramValue];
                        }
                    }
                }
                //排序条件
                if (!empty($param['orderByColumn'])) {
                    $order_column = trim($param['orderByColumn']);
                }
                if (!empty($param['isAsc'])) {
                    $order_sort = trim($param['isAsc']);
                }
                // 分页条件
                if (!empty($param['pageNum'])) $pageNum = intval($param['pageNum']);
                if (!empty($param['pageSize'])) $pageSize = intval($param['pageSize']);
            }

            if ($extMap) { // 查询条件合并
                $map = array_merge($map, $extMap);
            }

            $extSort = $extSort ?: [[$order_column, $order_sort]];// 指定排序

            $offset = ($pageNum - 1) * $pageSize; //分页开始
            $username = Yii::$app->user->identity->username;
            //拼接sql
            $query = Loginlog::find()->where('1')->andWhere(['login_name'=>$username]);
            if (!empty($map)) {
                $query = $this->bWhereFilter($query, $map);
            }
            //若开启了分页获取总数
            if ($pageList) {
                $total = $query->count();
            }
            if (!empty($select)) { //指定查询字段
                $query = $query->select($select);
            }
            $export = $param['isExport']??'0';
            if (!$export){
                if ($pageList) { //指定分页
                    $query = $query->offset($offset)->limit($pageSize);
                }
            }
            if (!empty($extSort)) { // 指定排序
                $orderBy = [];
                foreach ($extSort as $key => $val) {
                    if (is_array($val)) {
                        $orderBy[] = $val[0] . ' ' . $val[1];
                    } else {
                        $orderBy[] = $key . ' ' . $val;
                    }
                }
                $orderBy = implode(',', $orderBy);
                $query = $query->orderBy($orderBy);
            }


            //导出判断
            if($export){
                $list = $query->all();
                $exportData = $this->handelExport($list);
                return AdminExportApi::run(new $this->model(),$exportData);
            }else{
                $list = $query->asArray()->all();
            }

            if (!$pageList) {
                $total = count($list);
            }
            return commonApi::message('操作成功', true, $list, 0, '', ['total' => (int)$total]);
        }
    }
}
